package com.ebeitech.camera;

import java.util.ArrayList;
import java.util.List;

import android.content.Intent;
import android.graphics.BitmapFactory;
import android.graphics.PixelFormat;
import android.os.Bundle;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.GestureDetector;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.ScaleGestureDetector;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AbsListView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.TextView;

import com.ebeitech.doorapp.view.BaseActivity;
import com.ebeitech.doorapp.R;
import com.ebeitech.doorapp.view.OnInitializeListener;
import com.ebeitech.library.constant.SPConstants;
import com.ebeitech.library.util.ViewUtil;

public class QPIMediaActivity extends BaseActivity {

	private static final int MEDIA_MODE_VIDEO = 0;
	private static final int MEDIA_MODE_CAMERA = 1;
	private static final int MEDIA_MODE_VOICE = 2;
	
	private static final String TAG = "QPIMediaActivity";

	private ViewPager mViewPager;
	private View mModeView;
	private PagerAdapter mModeAdapter;

	private QPICameraFragment mCameraFragment;
	private VideoFragment mVideoFragment;
	private MediaRecorderFragment mRecorderFragment;

	private int mLastPositon = MEDIA_MODE_CAMERA;
	private List<MediaMode> mModes;
	private List<View> mModeViews;
	private int screenWidth;
	private int itemWidth;
	
	private boolean isSwitching;
	
	private GestureDetector mGestureDetector;
	private ScaleGestureDetector mScaleGestureDetector;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		if (savedInstanceState == null) {
			savedInstanceState = new Bundle();
		}
		savedInstanceState.putBoolean(SPConstants.IS_FIT_STATUS_BAR, false);
		super.onCreate(savedInstanceState);
		getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
		getWindow().setFormat(PixelFormat.TRANSLUCENT);
		getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
		setContentView(R.layout.ebei_activity_media);
		initView();

		mViewPager.setCurrentItem(mLastPositon);
		onViewSelected(mModes.get(mLastPositon).getType());
	}

	private void initView() {
		// TODO Auto-generated method stub
        isSwitching = false;
        mModes = new ArrayList<MediaMode>();
        Intent intent = getIntent();
        MediaMode videoMode = new MediaMode(getString(R.string.ebei_video), MEDIA_MODE_VIDEO);
        MediaMode cameraMode = new MediaMode(getString(R.string.ebei_camera), MEDIA_MODE_CAMERA);
        if (!intent.getBooleanExtra("hideVideo", false)) {
            mModes.add(videoMode);
        }
        if (!intent.getBooleanExtra("hideCamera", false)) {
            mModes.add(cameraMode);
        }
		if (!intent.getBooleanExtra("hideVoice", false)) {
			mModes.add(new MediaMode(getString(R.string.ebei_recording), MEDIA_MODE_VOICE));
		}

        if (mModes.contains(cameraMode) && mModes.size() > 1) {
			mLastPositon = MEDIA_MODE_CAMERA;
		} else {
			mLastPositon = 0;
		}
		
		mModeViews = new ArrayList<View>();
		screenWidth = ViewUtil.getScreenSize(this).widthPixels;
		itemWidth = BitmapFactory.decodeResource(getResources(), R.drawable.ebei_camera_start_normal).getWidth();
		mGestureDetector = new GestureDetector(this, new MyOnGestureListener());
		mScaleGestureDetector = new ScaleGestureDetector(this, mScaleGestureListener);
		for (int i = 0; i < mModes.size(); i++) {
			View parentView = getLayoutInflater().inflate(
					R.layout.ebei_view_media_mode, null);
			ImageView imageView = (ImageView) parentView
					.findViewById(R.id.iv_dot);
			imageView.setVisibility(i == mLastPositon ? View.VISIBLE
					: View.INVISIBLE);

			MediaMode mediaMode = mModes.get(i);
			TextView textView = (TextView) parentView.findViewById(R.id.tv_mode);
			textView.setText(mediaMode.getName());
			if (i == mLastPositon) {
				textView.setTextColor(getResources().getColor(
						R.color.ebei_camera_mode_text_color));
			}

			parentView.setLayoutParams(new AbsListView.LayoutParams(itemWidth,
					AbsListView.LayoutParams.WRAP_CONTENT));
			mModeViews.add(parentView);
		}

		mCameraFragment = new QPICameraFragment();
		mVideoFragment = new VideoFragment();
		mRecorderFragment = new MediaRecorderFragment();
		
		mCameraFragment.setOnInitializeListener(new OnInitializeListener() {
			
			@Override
			public void onFinished() {
				// TODO Auto-generated method stub
				isSwitching = false;
			}
		});
		mVideoFragment.setOnInitializeListener(new OnInitializeListener() {
			
			@Override
			public void onFinished() {
				// TODO Auto-generated method stub
				isSwitching = false;
			}
		});
		mRecorderFragment.setOnInitializeListener(new OnInitializeListener() {
			
			@Override
			public void onFinished() {
				// TODO Auto-generated method stub
				isSwitching = false;
			}
		});
		mVideoFragment.setIsVideo(true);

		mViewPager = (ViewPager) findViewById(R.id.viewpager_mode);
		mModeView = findViewById(R.id.container_mode);
		
		if (mModes.size() < 2) {
			mViewPager.setVisibility(View.GONE);
			mModeView.setVisibility(View.GONE);
		}

		LinearLayout.LayoutParams lp = (LayoutParams) mViewPager.getLayoutParams();
		lp.width = itemWidth;
		lp.leftMargin = (screenWidth - itemWidth) / 2;

		mViewPager.setLayoutParams(lp);
		// 1.设置幕后item的缓存数目
		mViewPager.setOffscreenPageLimit(mModes.size());
		// 2.设置页与页之间的间距
		mViewPager.setPageMargin(0);
		// 3.将父类的touch事件分发至viewPgaer，否则只能滑动中间的一个view对象
		mModeView.setOnTouchListener(new View.OnTouchListener() {
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				if (isSwitching) {
					return true;
				}
				boolean b = false;
				try {
					b = mViewPager.dispatchTouchEvent(event);
				} catch (Exception e) {
					// TODO: handle exception
					e.printStackTrace();
				}
				return b;
			}
		});
		mViewPager.setOnTouchListener(new View.OnTouchListener() {

			@Override
			public boolean onTouch(View arg0, MotionEvent arg1) {
				// TODO Auto-generated method stub
				if (arg1.getAction() == MotionEvent.ACTION_UP) {
					int x = (int) arg1.getX();
					int index = mViewPager.getCurrentItem();
					if (x < (screenWidth - itemWidth) / 2) {
						index = index
								- (((screenWidth - itemWidth) / 2 - x
										+ itemWidth - 1) / itemWidth);
						if (!isSwitching && index > -1 && index < mModes.size()) {
							mViewPager.setCurrentItem(index);
						}
					} else if (x > (screenWidth + itemWidth) / 2) {
						index = index
								+ ((x - (screenWidth + itemWidth) / 2
										+ itemWidth - 1) / itemWidth);
						if (!isSwitching && index > -1 && index < mModes.size()) {
							mViewPager.setCurrentItem(index);
						}
					}
					Log.i(TAG, "onTouch : index = " + index);
				}
				return false;
			}
		});
		// 4.设置Adapter
		mModeAdapter = new MediaViewPager();
		mViewPager.setAdapter(mModeAdapter);
		// 5.设置监听
		mViewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
			
			@Override
			public void onPageSelected(int position) {
				// TODO Auto-generated method stub
				MediaMode mediaMode = mModes.get(position);
				if (mLastPositon != position) {
					if (isSwitching) {
						return;
					}
					if (!isSwitching) {
						isSwitching = true;
					}
					
					View lastView = mModeViews.get(mLastPositon);
					TextView lastText = (TextView) lastView.findViewById(R.id.tv_mode);
					lastText.setTextColor(getResources()
							.getColor(R.color.ebei_white));
					lastView.findViewById(R.id.iv_dot).setVisibility(View.INVISIBLE);
					
					View selectView = mModeViews.get(position);
					TextView selectText = (TextView) selectView.findViewById(R.id.tv_mode);
					selectText.setTextColor(getResources().getColor(
							R.color.ebei_camera_mode_text_color));
					selectView.findViewById(R.id.iv_dot).setVisibility(View.VISIBLE);
					mModeAdapter.notifyDataSetChanged();

					onViewUnSelected(mModes.get(mLastPositon).getType());
					onViewSelected(mediaMode.getType());
					mLastPositon = position;
				}
			}
			
			@Override
			public void onPageScrolled(int arg0, float arg1, int arg2) {
				// TODO Auto-generated method stub
				/*if (mModeView != null) {
					mModeView.invalidate();
				}*/
			}
			
			@Override
			public void onPageScrollStateChanged(int arg0) {
				// TODO Auto-generated method stub
				
			}
		});

	}

	@Override
	public boolean onTouchEvent(MotionEvent event) {
		// TODO Auto-generated method stub
		if (mModes.size() < 2) {
			return super.onTouchEvent(event);
		}
        mGestureDetector.onTouchEvent(event);
        mScaleGestureDetector.onTouchEvent(event);
        return true;
	}
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		if (mViewPager.getCurrentItem() == MEDIA_MODE_VOICE) {
			return mRecorderFragment.onKeyDown(keyCode, event);
		}
		return super.onKeyDown(keyCode, event);
	}
	
	private void onViewSelected(int modeType) {
		FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
		switch (modeType) {
		case MEDIA_MODE_VIDEO:
			ft.add(R.id.media_container, mVideoFragment);
			break;
		case MEDIA_MODE_CAMERA:
			ft.add(R.id.media_container, mCameraFragment);
			break;
		case MEDIA_MODE_VOICE:
			ft.add(R.id.media_container, mRecorderFragment);
			break;
		default:
			break;
		}
		ft.commit();
	}

	private void onViewUnSelected(int modeType) {
		FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
		switch (modeType) {
		case MEDIA_MODE_VIDEO:
			ft.remove(mVideoFragment);
			break;
		case MEDIA_MODE_CAMERA:
			ft.remove(mCameraFragment);
			break;
		case MEDIA_MODE_VOICE:
			ft.remove(mRecorderFragment);
			break;
		default:
			break;
		}
		ft.commit();
	}

	class MediaViewPager extends PagerAdapter {

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return mModeViews.size();
		}

		@Override
		public boolean isViewFromObject(View arg0, Object arg1) {
			// TODO Auto-generated method stub
			return arg0 == arg1;
		}

		@Override
		public Object instantiateItem(ViewGroup container, final int position) {
			// TODO Auto-generated method stub
			container.addView(mModeViews.get(position));
			return mModeViews.get(position);
		}

		@Override
		public void destroyItem(ViewGroup container, int position, Object object) {
			// TODO Auto-generated method stub
			container.removeView(mModeViews.get(position));
		}

		@Override
		public int getItemPosition(Object object) {
			// TODO Auto-generated method stub
			return POSITION_NONE;
		}
	}

	class MyOnGestureListener extends SimpleOnGestureListener {
		
		@Override
		public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
			int index = mViewPager.getCurrentItem();
			if (e1.getX() - e2.getX() > 50) {
				// 向右滑动
				index++;
				if (!isSwitching && index > -1 && index < mModes.size()) {
					mViewPager.setCurrentItem(index);
				}
			} else if (e1.getX() - e2.getX() < -50) {
				// 向左滑动
				index--;
				if (!isSwitching && index > -1 && index < mModes.size()) {
					mViewPager.setCurrentItem(index);
				}
			}
			return false;
		}
		
		@Override
		public boolean onSingleTapUp(MotionEvent e) {
			// TODO Auto-generated method stub
			if (mModes.get(mLastPositon).getType() == MEDIA_MODE_CAMERA) {
				mCameraFragment.onSingleTapUp(e);
			}
			return false;
		}
		
	}
	
	private ScaleGestureDetector.SimpleOnScaleGestureListener mScaleGestureListener = new ScaleGestureDetector.SimpleOnScaleGestureListener() {

		@Override
		public boolean onScale(ScaleGestureDetector detector) {
			// TODO Auto-generated method stub
			if (mModes.get(mLastPositon).getType() == MEDIA_MODE_CAMERA) {
				mCameraFragment.onScale(detector);
			}
			return false;
		}
	};
	
	class MediaMode {
		
		private String name;
		private int type;

		public MediaMode() {
		}
		
		public MediaMode(String name, int type) {
			this.name = name;
			this.type = type;
		}

		public String getName() {
			return name;
		}

		public void setName(String name) {
			this.name = name;
		}

		public int getType() {
			return type;
		}

		public void setType(int type) {
			this.type = type;
		}

	}
	
}
